//
//  ConversationListVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/20.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "ConversationListVC.h"
#import "ConversationCell.h"
#import "YCMenuView.h"
#import "ChatListVC.h"
#import "ChatContentVC.h"
#import "SessionItem.h"
#import <LKDBHelper/LKDBHelper.h>
#import "DIYScanVC.h"
#import "FriendInfoListVC.h"
#import "NSDate+Debug.h"
#import "SearchFriendResultVC.h"
#import "YBApiManager+Chat.h"
#import "YBApiManager+Global.h"
#import "AddressListVC.h"
#import "BaseNavigationController.h"
#import "UIViewController+ScanQR_Logic.h"

@interface ConversationListVC ()<IMManagerDelegate, UISearchBarDelegate>

@property (nonatomic, strong) UISearchController *searchVC;
@property (nonatomic, weak) SearchFriendResultVC *resultVC;
@property (nonatomic, assign) CFRunLoopObserverRef observerRef;

@end

@implementation ConversationListVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    [self setupDatasource];
    [self setupSearchVc];
    [IMManager shareManager].isReady = YES;
    [IMManager shareManager].bindUidDelegate = self;
    [self imManagerNeedBindUserId];
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_NewSession_created object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        SessionItem *s = x.object;
        SessionItem *oldS = nil;
        BOOL hasSession = NO;
        for (SessionItem *session in self.dataSource) {
            if ([session.group_id isEqualToString:s.group_id] == YES) {
                hasSession = YES;
                oldS = session;
                break;
            }
        }
        if (hasSession == YES) {
            NSInteger row = [self.dataSource indexOfObject:s];
            if (row != 0) {
                [self.dataSource removeObject:oldS];
                [self.dataSource insertObject:s atIndex:0];
                [self.tableView reloadData];
            } else {
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            }
        } else {
            [self.dataSource insertObject:s atIndex:0];
            if (s.groupName.isHaveStr == NO ) {
                [kUsermanager getGroupWithGroupId:s.group_id callbackBlock:^(GroupItem * _Nonnull item) {
                    s.groupIcon = item.avatar;
                    s.groupName = item.name;
                    [s updateToDB];
                }];
                [self.tableView reloadData];
            } else {
                [self.tableView reloadData];
            }
        }
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_DeleteFriend object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
       @strongify(self);
        FriendItem *item = x.object;
        for (SessionItem *session in self.dataSource) {
            if ([item.group_id isEqualToString:session.group_id] == YES) {
                [self.dataSource removeObject:session];
                [self.tableView reloadData];
                break;
            }
        }
    }];
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_DeleteGroupChat object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
       @strongify(self);
        GroupItem *group = x.object;
        for (SessionItem *session in self.dataSource) {
            if ([group.group_id isEqualToString:session.group_id] == YES) {
                [self.dataSource removeObject:session];
                [self.tableView reloadData];
                break;
            }
        }
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
       @strongify(self);
        [self.tableView reloadData];
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_Friend_Info_Changed object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        FriendItem *item = x.object;
        for (SessionItem *session in self.dataSource) {
            
            if ([item.group_id isEqualToString:session.group_id] == YES) {
                [kUsermanager getGroupInfoWithGroupId:session.group_id needUpdate:YES callbackBlock:^(GroupItem * _Nonnull item) {
                    session.groupName = item.name;
                    session.groupIcon = item.avatar;
                    [session updateToDB];
                }];
                break;
            }
        }
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_GroupChatInfo_updated object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        GroupItem *group = x.object;
        for (SessionItem *obj in self.dataSource) {
            if ([obj.group_id isEqualToString:group.group_id] == YES) {
                obj.groupIcon = group.avatar;
                obj.groupName = group.name;
                [obj updateToDB];
                [self.tableView reloadData];
                break;
            }
        }
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_CleanAll object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
       @strongify(self);
        [self.dataSource removeAllObjects];
        [self.tableView reloadData];
    }];
    
    for (SessionItem *session in self.dataSource) {
        [kUsermanager getGroupInfoWithGroupId:session.group_id needUpdate:YES callbackBlock:^(GroupItem * _Nonnull item) {
            session.groupIcon = item.avatar;
            session.groupName = item.name;
            [session updateToDB];
        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)setupUI {
    [self.tableView customRegisterClassWithName:@"ConversationCell"];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.k_img(UIImage.k_imgName(@"tab_plus"));
    [btn addTarget:self action:@selector(didClickRightBarBtnItemAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}
- (void)setupDatasource {
    [[IMManager shareManager] addIMDelegate:self];
    self.dataSource = [SessionItem searchWithWhere:nil orderBy:@"last_msg_time desc" offset:0 count:0];
    [self.tableView reloadData];
}


#pragma mark - tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConversationCell" forIndexPath:indexPath];
    cell.session = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ChatContentVC *chatvc = [ChatContentVC new];
    chatvc.session = self.dataSource[indexPath.row];
    @weakify(self);
    [chatvc setFrowardingMsgBlock:^(MsgModel * _Nonnull msgModel, FriendItem * _Nonnull friendItem) {
        @strongify(self);
        [self receiveForwardingMsg:msgModel friendItem:friendItem];
    }];
    [self.navigationController pushViewController:chatvc animated:YES];
    chatvc.session.unread_msg_count = 0;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除会话";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        SessionItem *session = self.dataSource[indexPath.row];
        [LBXAlertAction showAlertWithTitle:@"删除会话" msg:@"删除会话会同时删除聊天记录！" buttonsStatement:@[@"取消", @"确认删除"] chooseBlock:^(NSInteger buttonIdx) {
            if (buttonIdx == 1) {
                [self deleteConversationWithSession:session];
            }
        }];
    }
}

#pragma mark - actions
- (void)deleteConversationWithSession:(SessionItem *)session{
    
    BOOL isDelete = [MsgItem deleteWithWhere:@{@"group_id": session.group_id}];
    if (isDelete == NO) {
        [MBProgressHUD showTipMessageInView:@"删除会话失败，请重试" timer:1.5f];
        return;
    }
    isDelete = [SessionItem deleteWithWhere:@{@"group_id": session.group_id}];
    if (isDelete == NO) {
        [SessionItem deleteWithWhere:@{@"group_id": session.group_id}];
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.dataSource indexOfObject:session] inSection:0];
    [self.dataSource removeObject:session];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

}
- (void)didClickRightBarBtnItemAction {
    
    YCMenuAction *action1 = [YCMenuAction actionWithTitle:@"添加朋友" image:UIImage.k_imgName(@"new_add_normal") handler:^(YCMenuAction *action) {
        [self.navigationController pushViewController:[NSClassFromString(@"AddNewFriendVC") new] animated:YES];
    }];
    action1.highlightImage = UIImage.k_imgName(@"new_add_highlight");
    @weakify(self);
    YCMenuAction *addGroupAction = [YCMenuAction actionWithTitle:@"发起群聊" image:UIImage.k_imgName(@"new_group_normal") handler:^(YCMenuAction *action) {
        AddressListVC *selectFriendVC = AddressListVC.new;
        selectFriendVC.listType = 2;
        [selectFriendVC setDidClickCreateGroupChatBlock:^(NSArray * _Nonnull ids) {
            NSLog(@"ids = %@", ids);
            @strongify(self);
            [self createGroupChatWithUserIds:ids];
        }];
        UINavigationController *nv = [[BaseNavigationController alloc] initWithRootViewController:selectFriendVC];
        [self presentViewController:nv animated:YES completion:nil];
    }];
    addGroupAction.highlightImage = UIImage.k_imgName(@"new_group_highlight");
    YCMenuAction *action2 = [YCMenuAction actionWithTitle:@"扫一扫" image:UIImage.k_imgName(@"new_qr_normal") handler:^(YCMenuAction *action) {
//        DIYScanVC *scanVC = [DIYScanVC new];
        
        @strongify(self);
        [self qr_showScanQRVC];
        
//        scanVC.scanResult = ^(NSString *result) {
//            NSDictionary *resultDic = [result mj_JSONObject];
//            NSString *qr_type = [resultDic objectForKey:@"qr_type"];
//            if ([qr_type isEqualToString:@"group"] == YES) {
//                GroupItem *group = [GroupItem mj_objectWithKeyValues:resultDic];
//
//            } else if ([qr_type isEqualToString:@"group"] == YES) {
//                [self showFriendInfoVCWithType:2 friendItem:[FriendItem mj_objectWithKeyValues:resultDic] from:@"1"];
//            }
//        };
//        [self.navigationController pushViewController:scanVC animated:YES];
    }];
    action2.highlightImage = UIImage.k_imgName(@"new_qr_highlight");
    
    YCMenuView *view = [YCMenuView menuWithActions:@[action1, addGroupAction, action2] width:135 relyonView:self.navigationItem.rightBarButtonItem];
    view.textColor = UIColor.k_t2Color;
    
    [view show];
}
- (void)showFriendInfoVCWithType:(NSInteger)type friendItem:(FriendItem *)item from:(NSString *)from {
    FriendInfoListVC *VC = [FriendInfoListVC new];
    VC.user = item;
    VC.from = from;
    VC.listType = type;
    
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)receiveForwardingMsg:(MsgModel *)msgModel friendItem:(FriendItem *)item {
    SessionItem *target = nil;
    for (SessionItem *session in self.dataSource) {
        if ([session.group_id isEqualToString:msgModel.msg.group_id]) {
            target = session;
            break;
        }
    }
    MsgItem *lastMsg = nil;
    if (target) {
        lastMsg = [MsgItem searchSingleWithWhere:@{@"group_id": target.group_id} orderBy:@"createtime desc"];
    }
    if (target == nil || [NSDate currentIsDisplayTimeWithTimestamp:lastMsg.createtime] == YES) {
        MsgModel *timeModel = [MsgModel new];
        MsgItem *timeMsg = [MsgItem new];
        timeModel.msg = timeMsg;
        timeMsg.type = MsgType_Time;
        timeMsg.createtime = [NSString kk_stringWithInteger:msgModel.msg.createtime.longLongValue-1];
        timeMsg.message_id = [[IMManager shareManager] getSendMessageId];
        timeMsg.group_id = msgModel.msg.group_id;
        
        [MsgItem insertToDB:timeMsg];
    }
    
    
    if (target) {
        target.last_msg_time = msgModel.msg.createtime;
        target.last_msg_id = msgModel.msg.message_id;
        NSInteger row = [self.dataSource indexOfObject:target];
        
        if (row != 0) {
            [self.dataSource removeObject:target];
            [self.dataSource insertObject:target atIndex:0];
            [self.tableView reloadData];
        } else {
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
    } else {
        target = [SessionItem new];
        
        target.last_msg_time = msgModel.msg.createtime;
        target.group_id = msgModel.msg.group_id;
        target.groupName = item.displayName;
        target.groupIcon = item.avatar;
        target.last_msg_id = msgModel.msg.message_id;
        
        
        [SessionItem insertToDB:target];
        [self.dataSource insertObject:target atIndex:0];
        [self.tableView reloadData];
    }
    
}
#pragma mark - immanager delegate
- (void)imManager:(IMManager *)manager receiveMsg:(MsgModel *)msgModel {
    
    if (msgModel.msg.type == MsgType_Time || msgModel.msg.type == MsgType_Tip) {
        return;
    }
    
    SessionItem *target = nil;
    for (SessionItem *session in self.dataSource) {
        if ([session.group_id isEqualToString:msgModel.msg.group_id]) {
            target = session;
            break;
        }
    }
    if (target) {
        target.last_msg_time = msgModel.msg.createtime;
        target.last_msg_id = msgModel.msg.message_id;
        NSInteger row = [self.dataSource indexOfObject:target];
        [kUsermanager getGroupWithGroupId:msgModel.msg.group_id callbackBlock:^(GroupItem * _Nonnull item) {
            target.groupIcon = item.avatar;
            target.groupName = item.name;
            [target updateToDB];
        }];
        
        if (msgModel.msg.is_read == NO && [target.group_id isEqualToString:kUsermanager.currentSession.group_id] == NO) {
            target.unread_msg_count++;
        }
        
        if (row != 0) {
            [self.dataSource removeObject:target];
            [self.dataSource insertObject:target atIndex:0];
            [self.tableView reloadData];
        } else {
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
        
        [target updateToDB];
        
    } else {
        target = [SessionItem new];
        
        target.last_msg_time = msgModel.msg.createtime;
        target.group_id = msgModel.msg.group_id;
//        target.create_id = kUsermanager.me.ID;
        target.groupName = msgModel.msg.send_user_id;
        target.last_msg_id = msgModel.msg.message_id;
        target.unread_msg_count = 1;
        [SessionItem insertToDB:target];
        [self.dataSource insertObject:target atIndex:0];
        [self.tableView reloadData];
        
        [kUsermanager getGroupWithGroupId:msgModel.msg.group_id callbackBlock:^(GroupItem * _Nonnull item) {
            target.groupIcon = item.avatar;
            target.groupName = item.name;
            target.isGroupChat = item.status;
            [target updateToDB];
            [self.tableView reloadData];
        }];
    }
}
- (void)imManager:(IMManager *)manager connectStatusChanged:(IMConnectStatus)connectStatus {
    if (connectStatus == IMConnectStatus_Connected) {
        self.title = @"畅聊";
    } else if (connectStatus == IMConnectStatus_Connecting) {
        self.title = @"连接中...";
    } else if (connectStatus == IMConnectStatus_Failed) {
        self.title = @"连接失败";
    } else if (connectStatus == IMConnectStatus_KickedOffline) {
        self.title = @"已掉线";
    }
}
- (void)imManager:(IMManager *)manager receiveFriendStatusMsg:(MsgItem *)msg {
    if (msg.type == MsgType_Friend_delete) {
        [kUsermanager updateFriendList];
        SessionItem *target = nil;
        for (SessionItem *session in self.dataSource) {
            if ([session.group_id isEqualToString:msg.group_id] == YES) {
                [SessionItem deleteWithWhere:@{@"group_id": session.group_id}];
                target = session;
                break;
            }
        }
        if (target) {
            [self.dataSource removeObject:target];
            [self.tableView reloadData];
        }
    }
}

- (void)imManager:(IMManager *)manager recallMsg:(MsgItem *)msg {

    for (SessionItem *session in self.dataSource) {
        if ([session.group_id isEqualToString:msg.group_id] == YES) {
            if (session.last_msg_id == 0) {
                session.last_msg_id = msg.message_id;
                [session updateToDB];
            }
            if (session.last_msg_id == msg.message_id) {
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[self.dataSource indexOfObject:session] inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                break;
            }
        }
    }
}
- (void)imManager:(IMManager *)manager readMsg:(MsgItem *)msg {
    for (SessionItem *session in self.dataSource) {
        if ([session.group_id isEqualToString:msg.group_id] == YES) {
            session.unread_msg_count = 0;
            [session updateToDB];
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[self.dataSource indexOfObject:session] inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            break;
        }
    }
}

- (void)imManagerNeedBindUserId {
    
    if (IMManager.shareManager.isBindUserId == YES ||
        IMManager.shareManager.isReady == NO ||
        IMManager.shareManager.client_id.isHaveStr == NO) {
        return;
    }
//    NSString *ds = nil;
//    if (IMManager.shareManager.isNeedPullMsg == YES) {
//        NSMutableArray *dsArr = [NSMutableArray arrayWithCapacity:self.dataSource.count];
//        for (SessionItem *session in self.dataSource) {
//            NSDictionary *dic = @{@"group_id": session.group_id?:@"",
//                                  @"createtime": session.last_msg_time
//                                  };
//            [dsArr addObject:dic];
//        }
//        ds = [dsArr mj_JSONString];
//    }
//    @weakify(self);
    IMManager.shareManager.isBindUserId = YES;
    [[YBApiManager.shareManager bindUserIdWithCliendId:[IMManager shareManager].client_id ds:@"" get:IMManager.shareManager.isNeedPullMsg] subscribeNext:^(id  _Nullable x) {
//        @strongify(self);
        [IMManager shareManager].isBindUserId = YES;
        [IMManager shareManager].isNeedPullMsg = NO;
        
    } error:^(NSError * _Nullable error) {
        [IMManager shareManager].isBindUserId = NO;
    }];
}


#pragma mark search

- (void)setupSearchVc {
    self.navigationController.navigationBar.translucent = NO;
    
    self.extendedLayoutIncludesOpaqueBars = !self.navigationController.navigationBar.translucent;
    //    [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"取消"];
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTintColor:UIColor.k_t2Color];
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTitle:@"取消"];
    
    SearchFriendResultVC *resultVC = [SearchFriendResultVC new];
    resultVC.tbvc = self;
    @weakify(self);
    [resultVC setDidSelectFriendItemBlock:^(FriendItem * _Nonnull item) {
        @strongify(self);
        [self showFriendInfoVCWithType:2 friendItem:item from:@"0"];
    }];
    self.resultVC = resultVC;
    self.searchVC = [[UISearchController alloc] initWithSearchResultsController:resultVC];
    
    self.searchVC.searchResultsUpdater = resultVC;
    self.searchVC.searchBar.delegate = self;
    self.searchVC.delegate = resultVC;
    
    
    // 1.设置placeholder
    self.searchVC.searchBar.placeholder = @"搜索好友";
    
    // 2.设置searchBar的背景透明
    [self.searchVC.searchBar setBackgroundImage:UIImage.k_imgFillColor(UIColor.whiteColor, CGSizeMake(ScreenWidth, 64))];
    self.searchVC.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    
    // 3.设置搜索框文字的偏移
    self.searchVC.searchBar.searchTextPositionAdjustment = UIOffsetMake(3, 0);
    
    // 4.设置搜索框图标的偏移
    //    CGFloat offsetX = (self.view.bounds.size.width - 200 - 32) / 2;
    //    [self.searchVC.searchBar setPositionAdjustment:UIOffsetMake(offsetX, 0) forSearchBarIcon:UISearchBarIconSearch];
    
    // 5.取消按钮和文本框光标颜色
    //    self.searchVC.searchBar.tintColor = UIColor.k_t1Color;
    //    self.searchVC.searchBar.barTintColor = UIColor.k_t1Color;
    
    // 6.设置搜索文本框背景图片 [圆形的文本框只需要设置一张圆角图片就可以了]
    
    [self.searchVC.searchBar setSearchFieldBackgroundImage:[UIImage.k_imgFillColor(UIColor.k_hexColor(0xf0f0f0), CGSizeMake(ScreenWidth - 100, 36)) imageWithCornerRadius:36/2] forState:UIControlStateNormal];
    // 7.设置搜索按钮
    UIImage *searchImg = [[UIImage imageNamed:@"new_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.searchVC.searchBar setImage:searchImg forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    
    [self.searchVC.searchBar sizeToFit];
    
    // 2.Install the search bar
//    if ([self.navigationItem respondsToSelector:@selector(setSearchController:)]) {
//        // 2.1 For iOS 11 and later, wo place the search bar in the navigation bar
//        if (@available(iOS 11.0, *)) {
//            self.navigationItem.searchController = self.searchVC;
//            // 2.2 Set the search bar visible all the time
//            self.navigationItem.hidesSearchBarWhenScrolling = NO;
//        }

//        // 2.3 Hide line view
//        __weak typeof(self) weakSelf = self;
//        self.observerRef = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, true, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
//
//            NSLog(@"kCFRunLoopBeforeWaiting");
//            BOOL targetView = [weakSelf barGroudView:weakSelf.navigationController.view];
//            if (targetView) {
//                CFRunLoopRemoveObserver(CFRunLoopGetMain(), observer, kCFRunLoopDefaultMode);
//            }
//        });
//        CFRunLoopAddObserver(CFRunLoopGetMain(), self.observerRef, kCFRunLoopDefaultMode);

//    }
//    else {
        UIView *v = [[YBBaseView alloc] initWithFrame:self.searchVC.searchBar.bounds];
        [v addSubview:self.searchVC.searchBar];
    v.backgroundColor = UIColor.whiteColor;
    self.view.backgroundColor = self.navigationController.view.backgroundColor;
    [resultVC setViewWillPresentBlock:^{
        @strongify(self);
        self.view.backgroundColor = UIColor.whiteColor;
    }];
    [resultVC setViewWillDisPresentBlock:^{
        @strongify(self);
        self.view.backgroundColor = self.navigationController.view.backgroundColor;
    }];
        [self.view addSubview:v];
    [v mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        } else {
            make.top.mas_offset(0);
        }
        make.left.right.mas_offset(0);
        make.height.mas_equalTo(56);
    }];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
        make.top.equalTo(v.mas_bottom);
    }];
    
//    self.tableView.tableHeaderView = v;
//    }

    // 3.It is usually good to set the presentation context
    self.definesPresentationContext = YES;
    
    // 8.拿到搜索文本框
    UITextField *searchField = [self.searchVC.searchBar valueForKey:@"_searchField"];
    //    // 9.设置取消按钮文字
    //    [self.searchVC.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
    //
    searchField.font = [UIFont systemFontOfSize:14];
}
- (BOOL)barGroudView:(UIView *)targetView {
    for (UIView *sView in targetView.subviews) {
        if ([sView isKindOfClass:NSClassFromString(@"_UINavigationControllerPaletteClippingView")]) {
            if (sView.subviews.count > 0 && sView.subviews[0].subviews.count > 0 && sView.subviews[0].subviews[0].subviews.count > 1) {
                sView.subviews[0].subviews[0].subviews[1].hidden = YES;
                return YES;
            }
        }
    }
    
    return NO;
}

#pragma mark - group chat
- (void)createGroupChatWithUserIds:(NSArray *)ids {
    NSMutableString *userids = [[NSMutableString alloc] init];
    for (NSString *uid in ids) {
        [userids appendFormat:@"%@,",uid];
    }
    [userids deleteCharactersInRange:NSMakeRange(userids.length-1, 1)];
    @weakify(self);
    [[YBApiManager.shareManager createGroupChatWithGroupUserIds:userids] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [MBProgressHUD showActivityMessageInView:@""];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInWindow:@"创建成功" timer:1.0f];
        [kUsermanager updateGroupChatList];
        NSDictionary *dataDic = [x objectForKey:@"data"];
        [self createGroupChatSuccessWithGroupInfo:dataDic];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInWindow:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInWindow:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (void)createGroupChatSuccessWithGroupInfo:(NSDictionary *)groupInfo {
    
    SessionItem *session = [SessionItem new];
    session.group_id = groupInfo[@"group_id"];
    session.groupIcon = groupInfo[@"avatar"];
    session.groupName = groupInfo[@"name"];
    session.isGroupChat = YES;
    [SessionItem insertToDB:session];
    
    ChatContentVC *chatVC = [ChatContentVC new];
    chatVC.session = session;
    
    [self.dataSource insertObject:session atIndex:0];
    
    [kUsermanager getGroupWithGroupId:session.group_id callbackBlock:^(GroupItem * _Nonnull item) {
        session.groupIcon = item.avatar;
        session.groupName = item.name;
        [session updateToDB];
        [self.tableView reloadData];
    }];
    [self.tableView reloadData];
    [self.navigationController pushViewController:chatVC animated:YES];
}
@end
